$(function() {
    var webSite="http://api.hexfuture.com";
    
    var exercisePoolId = getUrlParam("exercisePoolId");
    template.helper('urlFormat', function(date, format) {
        
        // var date = { size: 2, value: format + "|" + date };
        // return qr.toDataURL(date);
        return "/create_qrcode?text=" + format + "|" + date + "&size=" + 2;
    });
    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
        var r = window.location.search.substr(1).match(reg);  //匹配目标参数
        if (r != null) return unescape(r[2]); return null; //返回参数值
    }
    function Init(params) {
        return $.ajax({
            type: "get",
            dataType: "json",//4295865427
            url: webSite+"/ExerciseInPoolsModel/" + exercisePoolId + "?ssotoken=Jiyuan",
            //data: "id=" + id,
            //complete :function(){$("#load").hide();},//AJAX请求完成时隐藏loading提示
            success: function(data) {
                var html = template('exerciselist', data);
                $("#content").html(html);
                InitExercise();
            }
        })
    }

    function InitExercise() {
        $(".hex_exercise").each(function() {
            var eKey = $(this).attr("hex_exerciseid");
            GetExercise(eKey);
        })

    }
    function GetExercise(eid) {
        $.ajax({
            type: "get",
            dataType: "json",
            url: webSite+"/Exercises/Get/" + eid + "?ssotoken=Jiyuan",
            //data: "id=" + id,
            //complete :function(){$("#load").hide();},//AJAX请求完成时隐藏loading提示
            success: function(data) {
                var source;
                if (data.ET == "FillBlank") {
                    source = template('fillblankExercise', data);
                }
                else if (data.ET == "Judgment") {
                    source = template('JudgmentExercise', data);
                }
                else if (data.ET == "Subjective") {
                    source = template('SubjectiveExercise', data);
                }
                else if (data.ET == "Program") {
                    source = template('ProgramExercise', data);
                }
                else if (data.ET == "ChoiceFillBlank") {
                    source = template('ChoiceFillBlankExercise', data);
                }
                else if (data.ET == "Compute") {
                    source = template('ComputeExercise', data);
                }
                else {
                    source = template('choiceExercise', data);
                }
                $("[hex_exerciseid='" + eid + "']").first().html(source);

                $("[hex_exerciseid='" + eid + "'] .hex_cexercise").each(function() {
                    var eKey = $(this).attr("hex_exerciseid");
                    GetExercise(eKey);
                })
            }
        })
    }
    jiankong();
    Init();
    function convertImagesToBase64() {
        contentDocument = document.getElementById("content");
        var regularImages = contentDocument.querySelectorAll("img");
        var canvas = document.createElement('canvas');
        var ctx = canvas.getContext('2d');
        [].forEach.call(regularImages, function(imgElement) {

            // var dataURL;
            // try {
            //     ctx.clearRect(0, 0, canvas.width, canvas.height);
            //     canvas.width = imgElement.width;
            //     canvas.height = imgElement.height;
            //     ctx.drawImage(imgElement, 0, 0);
            //     dataURL = canvas.toDataURL();
            // } catch (err) {
            //     // document.writeln("Error name: " + err.name + "");
            //     // document.writeln("Error message: " + err.message);
            //     console.log(imgElement);
            // }
            // finally {
            //     imgElement.setAttribute('src', dataURL);
            // }
            
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            canvas.width = imgElement.width;
            canvas.height = imgElement.height;
            ctx.drawImage(imgElement, 0, 0);
            var dataURL = canvas.toDataURL();
            imgElement.setAttribute('src', dataURL);
        })
        canvas.remove();
    }
    function GetDocx() {
        // var time = Date.now();
        // console.log(time);
        // $.post("/test", { html: $("#content").html(), time: time }, function (data) {
        //     //console.log("回来了" + data);
        // });
        // var html = "<a href='/docx/" + time + ".docx'>点击下载</a>";
        // $("#url").html(html);
        convertImagesToBase64();
        $("#hidden_html").val($("#content").html());
        $("#url").show();
    }
    function jiankong(params) {
        //前提：所有ajax请求都是用jquery的$.ajax发起的，而非原生的XHR；
        var ajaxBack = $.ajax;
        var ajaxCount = 0;
        var allAjaxDone = function() {
            // $.post("/test",{html:$("#content").html()},function(date){
            //     alert(date);
            // });
            GetDocx();
        } //一行代码，就可以知道所有ajax请求什么时候结束
        //由于get/post/getJSON等，最后还是调用到ajax，因此只要改ajax函数即可
        $.ajax = function(setting) {
            ajaxCount++;
            var cb = setting.complete;
            setting.complete = function() {
                if ($.isFunction(cb)) { cb.apply(setting.context, arguments); }
                ajaxCount--;
                $("#state").text(ajaxCount);
                if (ajaxCount < 5 && $.isFunction(allAjaxDone)) {
                    allAjaxDone();
                }
            }
            ajaxBack(setting);
        }
    }

})